package name.vaccari.matteo.tai.phonedirectory.controllers;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import name.vaccari.matteo.tai.phonedirectory.model.PeopleRepository;
import name.vaccari.matteo.tai.phonedirectory.model.Person;
import name.vaccari.matteo.tai.phonedirectory.network.Servlet;
import name.vaccari.matteo.tai.phonedirectory.views.xpath.XmlDocument;

import org.junit.Test;


public class PeopleServletTest {

	private final class EmptyRepository implements
			PeopleRepository {
		
		List<Person> people = new ArrayList<Person>();
		
		public List<Person> getPeople(int startIndex, int howMany) {
			return people;
		}

		public int getTotalPeople() {
			return people.size();
		}

		public void add(Person person) {
			people.add(person);
		}
	}

	@Test
	public void testOutputContainsHtmlDocument() throws Exception {
		Servlet servlet = new PeopleServlet(new EmptyRepository());
		String body = servlet.doGet("/list");
		XmlDocument document = new XmlDocument(body);
		assertEquals("Phone Directory", document.getNodeText("/html/head/title"));
	}
	
	@Test
	public void shouldReturnAFormWhenPathIsSlashNew() throws Exception {
		Servlet servlet = new PeopleServlet(new EmptyRepository());
		String body = servlet.doGet("/new");
		XmlDocument document = new XmlDocument(body);
		assertEquals(1, document.getNodeList("//form[@method='post']").getLength());
	}
	
	@Test
	public void shouldCreateANewPersonFromData() throws Exception {
		EmptyRepository repository = new EmptyRepository();
		Servlet servlet = new PeopleServlet(repository);
		assertEquals(0, repository.getTotalPeople());
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("firstName", "Paolino");
		params.put("lastName", "Paperino");
		String redirectUrl = servlet.doPost("/create", params );
		
		assertEquals("/list", redirectUrl);
		assertEquals(1, repository.getTotalPeople());
		List<Person> found = repository.getPeople(0, 1);
		
		assertEquals("Paolino", found.get(0).getFirstName());
	}
}
